/*******************************************************************************
 * Copyright (c) 2014 lifeng (lifengsofts@gmail.com)
 * See the file licenses/license.txt for copying permission.
 ******************************************************************************/
package cn.woblog.android.httputils.domain;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;

import android.annotation.SuppressLint;
import android.os.AsyncTask;

import cn.woblog.android.httputils.RequestTask;
import cn.woblog.android.httputils.callback.ICallback;

public class Request {
	public RequestTool tool;

	public Request(String url) {
		this(url, RequestMethod.GET);
	}

	public Request(String url, RequestMethod method) {
		this(url, method, RequestTool.HTTPCLIENT);
	}

	public Request(String url, RequestMethod method, RequestTool tool) {
		// this.url = URLEncoder.encode(url);
		int indexOf = url.indexOf("?");
		if (indexOf != -1) {
			String params = url.substring(indexOf, url.length());
			String host = url.substring(0, indexOf);
			url = host + params;
		}
		this.url = url;
		this.method = method;
		this.tool = tool;
	}

	/**
	 * http request method
	 * 
	 * @author lifeng
	 * @version 1.0, Oct 18, 2014 11:41:41 AM
	 * 
	 */
	public enum RequestMethod {
		GET, POST, DELETE, PUT
	};

	public enum RequestTool {
		HTTPCLIENT, HTTPURLCONNECTION
	};

	public RequestMethod method;
	public String url;
	public HttpEntity entiry;
	public Map<String, String> headers;
	public ICallback callback;
	public int mRetryCount = 0;
	public boolean isCancel;

	public Request setCallBack(ICallback callback) {
		this.callback = callback;
		return this;
	}

	/**
	 * add request header,the same key value will be replaced,do not remove
	 * other key
	 * 
	 * @author lifeng
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public Request addHeader(String key, String value) {
		if (headers == null) {
			headers = new HashMap<String, String>();
		}
		headers.put(key, value);
		return this;
	}

	@SuppressLint("NewApi")
	public void execute() {
		RequestTask requestTask = new RequestTask(this);
		// requestTask.execute();
		requestTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);
	}

	public void cancel(boolean isForce) {
		if (callback != null) {
			callback.cancel();
			this.isCancel = isForce;
		}
	}

	public void setRetryCount(int count) {
		mRetryCount = count;
	}

	// public Request setHeader(String key, String value) {
	// headers = new HashMap<String, String>();
	// headers.put(key, value);
	// return this;
	// }
}
